# -*- coding: utf-8 -*-
import logging
import threading
from zc_core.client.mongo_client import Mongo
from zc_core.model.items import ItemData, Sku

logger = logging.getLogger('DetailHelper')


class DetailHelper(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(DetailHelper, "_instance"):
            with DetailHelper._instance_lock:
                if not hasattr(DetailHelper, "_instance"):
                    DetailHelper._instance = object.__new__(cls)
        return DetailHelper._instance

    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            self.id_row_dict = dict()
            self.mongo = Mongo()
            coll = self.mongo.get_collection('item_data_pool')
            if coll:
                rows = coll.find({'spuId': {'$exists': True}})
                if rows:
                    for row in rows:
                        self.id_row_dict[row.get('_id')] = row

    def fill(self, item):
        # 商品数据
        if isinstance(item, ItemData) or isinstance(item, Sku):
            if item.get('skuId') and not item.get('spuId'):
                row = self.id_row_dict.get(item.get('skuId'))
                if row:
                    item['spuId'] = row.get('spuId', None)
                    item['unit'] = row.get('unit', None)
                    item['brandName'] = row.get('brandName', None)
                    item['brandId'] = row.get('brandId', None)

        return item

    # 关闭链接
    def close(self):
        self.mongo.close()
